package com.components.base.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


/**
 * description: 配套用的 跑马灯配套recyclerview
 */
class AutoMarqueeRecycleView : RecyclerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    )

    /**
     * 这个数组是记录横向滑动状态的
     */
    var flipStatus: MutableList<Int> = mutableListOf()

    private var recordStateListSize = 0

    /**动态记录标记数据的大小*/
    fun setRecordListSize(size: Int) {
        recordStateListSize = size
        for (i in 0 until size) {
            flipStatus.add(i, 0)
        }
    }

    /**
     * 上次执行动画的时间, 用于处理短时间内调用两次的bug
     */
    var lastAnimTime = 0L

    /**
     * 执行动画
     */
    fun doAllFlip() {
        if (flipStatus.all { it == 1 }) {
            val last = System.currentTimeMillis() - lastAnimTime
            if (last < 5000) {
                postDelayed({
                    doAllFlip()
                }, 5000 - last)
            } else {
                if (layoutManager is LinearLayoutManager) {
                    layoutManager?.let {
                        for (i in 0 until it.childCount) {//这里需要去判断文本是否还在横向滚动，如果在就跳出循环，未滚动就执行翻页
                            if (((it.getChildAt(i) as ViewGroup).getChildAt(0) as MarqueeView).isRoll) {
                                handlerMessage.post(task)//按秒计时调用，直到isRoll为false
                                break
                            }
                            //执行翻页前需要清空记录状态的数组
                            flipStatus.clear()
                            for (i in 0 until recordStateListSize) {
                                flipStatus.add(i, 0)
                            }
                            ((it.getChildAt(i) as ViewGroup).getChildAt(0) as MarqueeView).nextMove()
                        }
                        lastAnimTime = System.currentTimeMillis()
                    }
                }
            }
        }
    }

    val handlerMessage = Handler((if (Looper.myLooper() != null) Looper.myLooper() else Looper.getMainLooper())!!)

    private val task: Runnable = object : Runnable {
        override fun run() {
            handlerMessage.postDelayed(this, 1000) //设置延迟时间，此处是5秒
            //需要执行的代码
            doAllFlip()
        }
    }
}